﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Money.Interfaces;
using Money.Data;
using One.Framework;

namespace Money.Services
{
    public class CurrencyService : ICurrencyService
    {

        private Money.Data.MoneyManagerDataContext context;

        public CurrencyService()
        {
            context = new Money.Data.MoneyManagerDataContext();
        }

        public List<Money.Data.Currency> GetCurrencies()
        {
            return context.Currencies.ToList<Currency>();
        }

        public Currency GetCurrencyById(int id)
        {
            return context.Currencies.SingleOrDefault<Currency>(c => c.Id == id);
        }

        public void CreateCurrency(Currency item)
        {
            try
            {
                context.Currencies.InsertOnSubmit(item);
                context.SubmitChanges();
            }
            catch(Exception ex)
            {
                Logger.Error(ex.ToString());
                throw new Exception("Cannot create currency");
            }
        }

        public void DeleteCurrency(int id)
        {
            try
            {
                Currency item = GetCurrencyById(id);
                context.Currencies.DeleteOnSubmit(item);
                context.SubmitChanges();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
                throw new Exception("Cannot delete currency");
            }
        }

        public void UpdateCurrency(Currency item)
        {
            try
            {
                context.SubmitChanges();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
                throw new Exception("Cannot update currency");
            }
        }

        public List<Currency> GetCurrencies(string orderBy, string orderDirection, int page, int pageSize, out int totalRecords)
        {
            try
            {
                var query = from c in context.Currencies
                            select c;
                return query.OrderByPaging<Currency>(orderBy, orderDirection, page, pageSize, out totalRecords).ToList<Currency>();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
                throw new Exception("Cannot get currencies");
            }
        }

        public bool CanDelete(int id)
        {
            Currency item = GetCurrencyById(id);
            if (item != null)
            {
                if (item.Accounts.Count > 0)
                    return false;
            }
            return true;
        }
    }
}
